package com.lv.controller;

import com.lv.dao.UserMapper;
import com.lv.pojo.Cart;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;

@RestController
public class DataCon {
    @Resource
    private UserMapper userMapper;
    //处理添加至购物车的请求
    @RequestMapping("/addToCart/{watch}")
    public String addToCart(@PathVariable Integer watch, HttpSession session){
        //获得登录的用户名，通过security上下文
        String name = SecurityContextHolder.getContext().getAuthentication().getName();
        //查询购物车中是否有重复的订单
        Cart cart = userMapper.peoCart(name, watch);
        HashMap<String, Object> map = new HashMap<>();
        map.put("username",name);
        if(cart==null){
            //如果没有重复订单，则新增订单
            map.put("watch",watch);
            map.put("count",1);
            userMapper.addCart(map);
        }else{
            //有重复订单的情况话，修改订单的数量
            map.put("id",cart.getWatch().getWatch_id());
            map.put("count",cart.getCount()+1);
            userMapper.upCart(map);
        }

        List<Cart> cartList = userMapper.getCart(name);
        session.setAttribute("cartList",cartList);
        return "商品("+cartList.size()+")";
    }
    //从购物车中清除订单的请求
    @RequestMapping("/deCart/{id}")
    public String deCart(@PathVariable Integer id,HttpSession session){
        //首先查询订单的数量
        String name = SecurityContextHolder.getContext().getAuthentication().getName();
        Cart cart = userMapper.peoCart(name, id);
        HashMap<String, Object> map = new HashMap<>();
        map.put("username",name);
        map.put("id",id);
        //订单数量多于1单的情况下，减少订单数量
        if(cart.getCount()>1){
            map.put("count",cart.getCount()-1);
            userMapper.upCart(map);
        }else{
            //订单数量不大于1的情况下，删除订单
            userMapper.deCart(map);
        }
        List<Cart> cartList = userMapper.getCart(name);
        session.setAttribute("cartList",cartList);
        return "商品("+cartList.size()+")";
    }
}
